package com.yw.android.common.utils;


import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class SMSHelper {
    private static final String TAG = "SMSHelper";
    private static SMSHelper helper = null;
    private Context context = null;
    private SMSHelper.SMSReceiver receiver = null;

    private SMSHelper(Context context) {
        this.context = context;
    }

    public static synchronized SMSHelper get(Context context) {
        if (null == helper) {
            Context appctx = context.getApplicationContext();
            helper = new SMSHelper(appctx);
        }

        return helper;
    }

    public static int TelephonyManager_getDefaultSubId(Context context) {
        try {
            Class<?> mSubscriptionManagerClass = Class.forName("android.telephony.SubscriptionManager");
            Method method = mSubscriptionManagerClass.getDeclaredMethod("getDefaultSubId");
            method.setAccessible(true);
            int subId = (Integer) method.invoke((Object) null);
            FLOG.i("TelephonyManager_getDefaultSubId subId = " + subId);
            return subId;
        } catch (NoSuchMethodException var4) {
            FLOG.e("TelephonyManager_getDefaultSubId NoSuchMethodException" + var4);
        } catch (IllegalArgumentException var5) {
            FLOG.e("TelephonyManager_getDefaultSubId IllegalArgumentException" + var5);
        } catch (IllegalAccessException var6) {
            FLOG.e("TelephonyManager_getDefaultSubId IllegalAccessException" + var6);
        } catch (InvocationTargetException var7) {
            FLOG.e("TelephonyManager_getDefaultSubId InvocationTargetException" + var7);
        } catch (ClassNotFoundException var8) {
            FLOG.e("TelephonyManager_getDefaultSubId ClassNotFoundException" + var8);
        } catch (Exception var9) {
            var9.printStackTrace();
            FLOG.e("TelephonyManager_getDefaultSubId Exception" + var9);
        } catch (Throwable var10) {
            var10.printStackTrace();
            FLOG.e("TelephonyManager_getDefaultSubId Throwable" + var10);
        }

        return -1;
    }

    public synchronized boolean recvAuthCode(final SMSHelper.OnRecvListener listener) {
        if (null != this.receiver) {
            FLOG.i("unregister old receiver, register new");
            this.context.unregisterReceiver(this.receiver);
        }

        this.receiver = new SMSHelper.SMSReceiver() {
            public void onSMSReceived(String message) {
                if (!TextUtils.empty(message) && (message.contains("奇酷") || message.contains("酷云"))) {
                    listener.onReceived(SMSHelper.this.getAuthCode(message));
                    SMSHelper.this.context.unregisterReceiver(SMSHelper.this.receiver);
                    SMSHelper.this.receiver = null;
                }

            }
        };
        this.context.registerReceiver(this.receiver, SMSHelper.SMSReceiver.getIntentFilter());
        return true;
    }

    public synchronized boolean sendActivateMessage(final String address, final String ccid, final String imsi, final String deviceId, final Handler handler, final SMSHelper.OnSentListener listener) {
        final String prefix = "[address:" + address + "][ccid:" + ccid + "][imsi:" + imsi + "][deviceId:" + deviceId + "]";
        Executor.execute(new Executor.RunNoThrowable(prefix) {
            public void rundo() {
                int rcode = 0;
                long start = System.currentTimeMillis();
                long millis = 0L;
                String taskId = null;
                String simId = SMSHelper.this.buildSimId(ccid, imsi);

                try {
                    String content = SMSHelper.this.buildActivateContent(simId, deviceId);
                    SMSHelper.BlockSendTask task = new SMSHelper.BlockSendTask(SMSHelper.this.context, address, content);
                    taskId = task.send();
                    rcode = task.getResult(10L, TimeUnit.SECONDS);
                    millis = System.currentTimeMillis() - start;
                    FLOG.i(prefix + "][taskId:" + taskId + "][millis:" + millis + "] send activate message done(" + rcode + ")");
                } catch (Throwable var13) {
                    millis = System.currentTimeMillis() - start;
                    FLOG.e(prefix + "][taskId:" + taskId + "][millis:" + millis + "] build activate content failed(Throwable)", var13);
                } finally {
                    SMSHelper.this.handleSentCallback(rcode, simId, handler, listener);
                }

            }
        });
        return true;
    }

    private String buildSimId(String ccid, String imsi) {
        String simId = this.invalid(ccid) ? imsi : ccid;
        return this.invalid(simId) ? System.currentTimeMillis() + "" : simId;
    }

    private boolean invalid(String s) {
        return TextUtils.empty(s) || s.length() <= 6;
    }

    private String buildActivateContent(String simId, String deviceId) {
        simId = null == simId ? "" : simId;
        deviceId = null == deviceId ? "" : deviceId;
        StringBuffer sb = new StringBuffer(64);
        sb.append("ACTIVATE:").append(simId).append("@").append(deviceId);
        return sb.toString();
    }

    private void handleSentCallback(final int rcode, final String simId, Handler handler, final SMSHelper.OnSentListener listener) {
        String prefix = "[rcode:" + rcode + "][simId:" + simId + "] callback for sent";
        if (null != handler) {
            handler.post(new Executor.RunNoThrowable(prefix) {
                public void rundo() {
                    if (null != listener) {
                        listener.onSent(rcode, simId);
                    }

                }
            });
        } else {
            try {
                if (null != listener) {
                    listener.onSent(rcode, simId);
                }
            } catch (Throwable var7) {
                FLOG.e(prefix + " failed(Throwable)", var7);
            }
        }

    }

    private String getAuthCode(String message) {
        String regular = "[^0-9]{1,}";
        String[] ss = message.split(regular);
        String[] arr$ = ss;
        int len$ = ss.length;

        for (int i$ = 0; i$ < len$; ++i$) {
            String s = arr$[i$];
            if (s.length() >= 4) {
                return s;
            }
        }

        return "";
    }

    public interface OnSentListener {
        void onSent(int var1, String var2);
    }

    public interface OnRecvListener {
        void onReceived(String var1);
    }

    private abstract static class SMSReceiver extends BroadcastReceiver {
        private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

        private SMSReceiver() {
        }

        public static IntentFilter getIntentFilter() {
            IntentFilter filter = new IntentFilter();
            filter.addAction("android.provider.Telephony.SMS_RECEIVED");
            return filter;
        }

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (null != action) {
                if ("android.provider.Telephony.SMS_RECEIVED".equals(action)) {
                    Object[] pdus = (Object[]) ((Object[]) intent.getExtras().get("pdus"));
                    int length = 0;
                    if (pdus != null) {
                        length = pdus.length;
                    }

                    SmsMessage[] messages = new SmsMessage[length];

                    for (int i = 0; i < length; ++i) {
                        messages[i] = SmsMessage.createFromPdu((byte[]) ((byte[]) pdus[i]));
                    }

                    StringBuffer sb = new StringBuffer();
                    SmsMessage[] arr$ = messages;
                    int len$ = messages.length;

                    for (int i$ = 0; i$ < len$; ++i$) {
                        SmsMessage smsMessage = arr$[i$];
                        sb.append(smsMessage.getDisplayMessageBody());
                    }

                    this.onSMSReceived(sb.toString());
                }
            }
        }

        public abstract void onSMSReceived(String var1);
    }

    private static class BlockSendTask extends FutureTask<Integer> {
        private String taskId = null;
        private Context context = null;
        private String address = null;
        private String content = null;
        private SMSHelper.BlockSendTask.SMSSentReceiver receiver = new SMSHelper.BlockSendTask.SMSSentReceiver();

        public BlockSendTask(Context context, String address, String content) {
            super(new Callable<Integer>() {
                public Integer call() throws Exception {
                    throw new IllegalStateException("this should never be called");
                }
            });
            this.taskId = "" + System.currentTimeMillis();
            this.context = context;
            this.address = address;
            this.content = content;
        }

        public String send() {
            try {
                this.doSendMessage();
            } catch (Throwable var2) {
                FLOG.e("[taskId:" + this.taskId + "][address:" + this.address + "][content:" + this.content + "] do send message failed(Throwable)", var2);
                this.set(1);
            }

            return this.taskId;
        }

        private void doSendMessage() {
            PendingIntent sent = PendingIntent.getBroadcast(this.context, 0, this.receiver.getIntent(this.taskId), 0);
            PendingIntent delivery = PendingIntent.getBroadcast(this.context, 0, new Intent(), 0);
            this.context.registerReceiver(this.receiver, this.receiver.getIntentFilter(this.taskId));
            this.doSendMessageForSubId(sent, delivery);
            FLOG.d("[taskId:" + this.taskId + "][address:" + this.address + "][content:" + this.content + "] send messsage ...");
        }

        private void doSendMessageForSubId(PendingIntent sent, PendingIntent delivery) {
            try {
                int subId = SMSHelper.TelephonyManager_getDefaultSubId(this.context);
                Class<?> mSmsManagerClass = Class.forName("android.telephony.SmsManager");
                Method method = mSmsManagerClass.getDeclaredMethod("getSmsManagerForSubscriptionId", Integer.TYPE);
                SmsManager sm = (SmsManager) method.invoke((Object) null, subId);
                sm.sendTextMessage(this.address, (String) null, this.content, sent, delivery);
            } catch (ClassNotFoundException var7) {
                var7.printStackTrace();
                FLOG.e("doSendMessageForSubId ClassNotFoundException" + var7);
            } catch (InvocationTargetException var8) {
                var8.printStackTrace();
                FLOG.e("doSendMessageForSubId InvocationTargetException" + var8);
            } catch (NoSuchMethodException var9) {
                var9.printStackTrace();
                FLOG.e("doSendMessageForSubId NoSuchMethodException" + var9);
            } catch (IllegalAccessException var10) {
                var10.printStackTrace();
                FLOG.e("doSendMessageForSubId IllegalAccessException" + var10);
            } catch (Exception var11) {
                var11.printStackTrace();
                FLOG.e("doSendMessageForSubId Exception" + var11);
            } catch (Throwable var12) {
                var12.printStackTrace();
                FLOG.e("doSendMessageForSubId Throwable" + var12);
            }

        }

        public int getResult(long timeout, TimeUnit unit) {
            if (!this.isDone()) {
                this.ensureNotOnMainThread();
            }

            byte var5;
            try {
                int var4 = (Integer) this.get(timeout, unit);
                return var4;
            } catch (InterruptedException var11) {
                FLOG.e("[taskId:" + this.taskId + "] wait future result failed(InterruptedException)", var11);
                byte var15 = -1;
                return var15;
            } catch (TimeoutException var12) {
                FLOG.e("[taskId:" + this.taskId + "] wait future result failed(TimeoutException)", var12);
                var5 = 5;
            } catch (ExecutionException var13) {
                FLOG.e("[taskId:" + this.taskId + "] wait future result failed(ExecutionException)", var13);
                return 1;
            } finally {
                this.context.unregisterReceiver(this.receiver);
            }

            return var5;
        }

        private void ensureNotOnMainThread() {
            Looper myLooper = Looper.myLooper();
            Looper mainLooper = Looper.getMainLooper();
            if (null != myLooper && myLooper == mainLooper) {
                IllegalStateException e = new IllegalStateException("calling on main thread may lead to deadlock and/or ANRs");
                throw e;
            }
        }

        private class SMSSentReceiver extends BroadcastReceiver {
            private static final String ACTION_PREFIX = "com.coolcloud.uac.android.SMS_SENT_";

            private SMSSentReceiver() {
            }

            public IntentFilter getIntentFilter(String id) {
                IntentFilter filter = new IntentFilter("com.coolcloud.uac.android.SMS_SENT_" + id);
                return filter;
            }

            public Intent getIntent(String id) {
                Intent intent = new Intent("com.coolcloud.uac.android.SMS_SENT_" + id);
                return intent;
            }

            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (null != action && action.startsWith("com.coolcloud.uac.android.SMS_SENT_")) {
                    String sentTaskId = action.replace("com.coolcloud.uac.android.SMS_SENT_", "");
                    int resultCode = this.getResultCode();
                    FLOG.d("[taskId:" + BlockSendTask.this.taskId + "][sentTaskId:" + sentTaskId + "][resultCode:" + resultCode + "] messsage sent ...");
                    if (BlockSendTask.this.taskId.equals(sentTaskId)) {
                        switch (resultCode) {
                            case -1:
                                BlockSendTask.this.set(0);
                                break;
                            case 0:
                            case 1:
                            case 2:
                            case 3:
                            case 4:
                            default:
                                BlockSendTask.this.set(1);
                        }
                    }
                }
            }
        }
    }
}
